package durak.server.control;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import durak.common.control.GameCommand;
import durak.common.model.Cards;
import durak.common.model.GameTableState;

/**
 * ClientPlayerControl class is responsible for receiving and forwarding to
 * handle client commands to server
 **/

public class PlayerControlHuman extends PlayerControl  {

	private boolean initialized = false;
	private GameCommand currentGameCommand;

	public PlayerControlHuman(Game gameSession) {
		super(gameSession);
	}

	@Override
	public void handleGameCommand(GameCommand command) {
		System.out.println(command.getPlayerName());
		super.getGameSession().getCommandHandler().handleReceivedMessageFromClient(this, command);
	}

	public void attack() {
		GameCommand command = new GameCommand(GameCommand.CommandType.S2C_ATTACK);
		sendCommand(command);
	}

	public void defend(Cards cards) {
		GameCommand command = new GameCommand(GameCommand.CommandType.S2C_DEFEND, cards);
		sendCommand(command);
	}

	public void notifyGameState(GameTableState gameState) {
		GameCommand command = new GameCommand(GameCommand.CommandType.S2C_NOTIFY_STATE);
		command.setGameState(gameState);
		sendCommand(command);
	}
	
	public void notifyRoundEnded(GameTableState gameState) {
		GameCommand command = new GameCommand(GameCommand.CommandType.S2C_ROUND_FINISHED);
		command.setGameState(gameState);
		sendCommand(command);
	}
	
	public void notifyGameEnded(GameTableState gameState) {
		GameCommand command = new GameCommand(GameCommand.CommandType.S2C_GAME_FINISHED);
		command.setGameState(gameState);
		sendCommand(command);
	}

	/**
	 * @param command
	 */
	private void sendCommand(GameCommand command) {
		command.setPlayerName(getPlayer().getName());
		command.setCards(super.getPlayer().getHand());
		command.setVersion((currentGameCommand != null) ? currentGameCommand.getVersion() + 1 : 1);
		if(command.getGameState() == null)
		{
			command.setGameState(currentGameCommand.getGameState());
		}
		currentGameCommand = command;
	}

	public void notifyGameTableFull() {
		GameCommand command = new GameCommand(GameCommand.CommandType.S2C_TABLE_FULL);
		sendCommand(command);
	}
	
	/**
	 * @return the initialized
	 */
	public synchronized boolean isInitialized() {
		return initialized;
	}

	/**
	 * @param initialized the initialized to set
	 */
	public synchronized void setInitialized(boolean initialized) {
		this.initialized = initialized;
	}

	/**
	 * @return the currentGameCommand
	 */
	public GameCommand getCurrentGameCommand() {
		return currentGameCommand;
	}

	}
